<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 当冲管理
 */
namespace app\api\controller;

use  Mscore\Core\Controller;
use  app\api\model\Daytrade as DaytradeModel;
use  app\api\model\Common as CommonModel;
use  app\api\model\Login as LoginModel;
use  Mscore\Core\Util\Util;
use  Mscore\Core\Util\Xcode;
use  Mscore\Core\Lang;

class DaytradeController extends Controller{

    private $model;
    private $login;
    private $error;
    private $success;
    private $controls;

    /**
     * 初始化自动连接方法
     * @param array $__construct 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->model = new DaytradeModel;
        $this->login = (new LoginModel)->isAuth();
        $this->header =get_all_headers();
        $this->header['language']=isset($this->header['language'])&&!empty($this->header['language'])?$this->header['language']:config('langs.default');
        Lang::init($this->header['language']);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
        $this->controls = config('daycontrol','/config/day');unset($this->controls['daycontrol']);
    }

    /**
     * 产品类别列表
     * @param array $catelist 
     * @param array $where 
     */ 
    public function catelist(){
        $pro=[];
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $pro = $this->model->catelist($where);
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1';
                $pro = $this->model->catelist($where,$page,$limit);
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 产品列表
     * @param array $daytrade 
     * @param array $where 
     */ 
    public function daytrade(){
        $pro=[];
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $pro = $this->model->daytrade($where);
                if(!empty($pro['data'][0]['titles'])){
                    $pro['data'][0]['title']=isset(json_decode($pro['data'][0]['titles'],true)[$this->header['language']])?json_decode($pro['data'][0]['titles'],true)[$this->header['language']]:$pro['data'][0]['title'];
                    unset($pro['data'][0]['titles']);
                }
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1 and a.status<3';
                if(!empty(post('cid'))){
                    $where .= ' and a.cid='.post('cid');
                }
                if(!empty(post('keyworld'))){
                    $where .= ' and ( a.title like "%'.post('keyworld').'%" or a.procode like "%'.post('keyworld').'%" ) ';
                }
                $pro = $this->model->daytrade($where,$page,$limit);
                $procode = '';
                foreach ($pro['data'] as $key => $value) {
                    if(!empty($value['titles'])){
                        $pro['data'][$key]['title']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['title'];  
                    }
                    $procode .= $value['procode'].',';
                    unset($pro['data'][$key]['titles']);
                }
                $this->success['data']=$pro['data'];
                $this->success['procode']=implode(',', array_filter(explode(',', $procode)));
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 当冲产品详情
     * @param array $daytradeinfo 
     * @param array $where 
    */ 
    public function daytradeinfo(){
        $id=post('id',false);
        switch (true) {
            case $id>0:
                $where = ' id='.$id;
                $pro = $this->model->daytradeinfo($where);
                if(!empty($pro['titles'])){
                    $pro['title']=isset(json_decode($pro['titles'],true)[$this->header['language']])?json_decode($pro['titles'],true)[$this->header['language']]:$pro['title'];
                    unset($pro['titles']);
                }
                if(!isset($pro['id'])){
                    return $this->echojson($this->error);
                }
                $info = $this->model->operateinfo('aid='.$this->login['pid'].' and proid='.$pro['id'].' and dels<1 and status=1','aid,auto,relate,fixmoney,fixtime');
                if(empty($info)){
                    $info = $this->model->operateinfo(' proid='.$pro['id'].' and dels<1 and status=1','aid,auto,relate,fixmoney,fixtime'); //獲取平台控制
                }
                
                //获取运营参数
                $key = $this->controls['key'];
                $operate=$this->model->execRedis('get',[$key]);
                $operate=json_decode($operate,true);
                if(!empty($operate)){
                    $pro['sn']=$operate['acode'];
                    $pro['fixmoney']=!empty($info['fixmoney'])?$info['fixmoney']:$operate['fixmoney'];
                    $pro['fixtime']=!empty($info['fixtime'])?$info['fixtime']:$operate['fixtime'];
                    $pro['timetype']=$operate['timetype'];
                    $pro['timelong']=$operate['timelong'];
                    $pro['endtime']=$operate['endtime'];
                    $pro['fshow']=$operate['fshow'];
                    $pro['settletime']=$operate['settletime'];
                    $pro['changewin']=$operate['changewin'];
                }
                $this->success['data']=$pro;
                $this->success['count']=1;
                return $this->echojson($this->success);
                break;
            default:
                return $this->echojson($this->error);
                break;
        }
    }

    /**
     * 获取k线图
     */
    public function getKdata(){
        $procode = post('procode',false);
        $page = post('page',1);
        $size = post('page_size',100);
        $time = post('time','1H'); //1M,5M,10M,15M,30M,1H,2H,4H,D,W,M
        if(!$procode){
            return $this->echojson($this->error);
        }
        $data = $this->model->getKdata($procode.'-'.$time.'-'.$page.'-'.$size);
        if(empty($data)){
            $data = $this->model->getApi("procode={$procode}&time={$time}&page={$page}&size={$size}&withlast=0");
            $data = json_decode($data,true);
            if(!isset($data['code']) || $data['code']!=200){
                $code = isset($data['code'])?$data['code']:103;
                $msg = isset($data['code'])?$data['msg']:'数据请求，接口无反应，请检查网络或其它错误';
                return $this->echojson(['code'=>$code,'msg'=>$msg]);
            }
            if(isset($data['data'])&&!empty($data['data'])){
                $settime=60*60;
                switch ($time) {
                    case '1M':
                        $settime=60;
                        break;
                    case '5M':
                        $settime=60*5;
                        break;
                    case '30M':
                        $settime=60*30;
                        break;
                    case '1H':
                        $settime=60*60;
                        break;
                    case 'D':
                        $settime=60*60*24;
                        break;
                    default:
                        $settime=60*60;
                        break;
                }
                $this->model->setKdata($procode.'-'.$time.'-'.$page.'-'.$size,$data['data'],$settime);
            }
            $data = $data['data'];
        }
        $this->success['data']=$data;
        return $this->echojson($this->success);
    }

    /**
     * 订单list
     * @param array $orderlist 
     * @param array $where 
     */ 
    public function orderlist(){
        switch (true) {
            case !empty(post('id')):
                $where = 'id='.post('id');
                $datalist = $this->model->list($where);
                $this->success['data']=$datalist['data'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' dels<1 and aid = '.$this->login['aid'].' and status>1';
                if(post('time')){
                    $time=post('time');
                    switch ($time){
                        case 1:
                            $where .= '';
                            break;
                        case 2:
                            $where .= " and (createtime BETWEEN CONCAT(CURDATE(),' 00:00:00') AND CONCAT(CURDATE(),' 23:59:59')) ";
                            break;
                        case 3:
                            $where .= ' and (TO_DAYS(NOW()) - TO_DAYS(createtime) = 1)';
                            break;
                        case 4:
                            $where .= ' and (WEEK(createtime) = WEEK(CURDATE()))';
                            break;
                        case 5:
                            $where .= " and DATE_FORMAT(createtime,'%Y-%m')= DATE_FORMAT(CURDATE(),'%Y-%m')";
                            break;
                        case 6:
                            $where .= " and (PERIOD_DIFF(DATE_FORMAT(NOW(),'%Y%m'),DATE_FORMAT(createtime,'%Y%m')) = 1)";
                            break;
                        default:
                            return $this->echojson($this->error);
                            break;
                    }
                    
                }
                $datalist = $this->model->list($where,$page,$limit);
                $this->success['data']=!empty($datalist['data'])?$datalist['data']:[];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 获取参数
     * @param array $getconfshow 
     * @param array $where 
     */ 
    public function getconfshow(){
        $daycontrol=(new CommonModel())->getBaseinfo('keyname="daycontrol"','content');
        $daycontrol=!empty($daycontrol)?$daycontrol['content']:$this->controls;
        $this->success['data']=$daycontrol;
        return $this->echojson($this->success); 
    }

    /**
     * 订单list
     * @param array $orderlistrun 
     * @param array $where 
     */ 
    public function orderlistrun(){
        switch (true) {
            case !empty(post('id')):
                $where = 'id='.post('id');
                $datalist = $this->model->list($where);
                $this->success['data']=$datalist['data'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' dels<1 and aid = '.$this->login['aid'].' and status<2 ';
                if(post('proname')){
                    $where .= ' and proname like "%'.post('proname').'%"';
                }
                $datalist = $this->model->list($where,$page,$limit);
                $this->success['data']=!empty($datalist['data'])?$datalist['data']:[];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 订单orderadd
     * @param array $orderadd 
     * @param array $where 
     */ 
    public function orderadd(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['proid'])) return $this->echoJson(Lang::get('Proempty'));
        if(empty($params['order_type'])) return $this->echoJson(Lang::get('Updown'));
        //判斷用户id
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['aid','amount','giftamount','pid','paypwd']);
        $control=(new CommonModel())->getBaseinfo('keyname="daycontrol"','content');
        $control=!empty($control)?$control['content']:$controls;
        //判斷支付密碼及驗證
        if($control['addorder']==1){
            if(empty($params['pay_password'])) return $this->echoJson(Lang::get('Paypwdempty'));
            if(empty($user['paypwd'])) return $this->echoJson(Lang::get('Paypwdset'));
            if (!Util::passwordVerify($params['pay_password'], $user['paypwd'])) return $this->echojson(Lang::get('Paypwderror'));
        }
        //初始化输赢参数
        $win=0;
        //獲取产品參數
        $pro = $this->model->daytradeinfo('id='.$params['proid'],['id','title','titles','procode']);
        if(empty($pro)) return $this->echojson(Lang::get('Parerror'));
        $pro['riskid']=0;
        if(!empty($pro)){
            $key = $this->controls['key'];
            $operate=$this->model->execRedis('get',[$key]);
            if(!empty($operate)){
                $operate=json_decode($operate,true);
                $pro['timelong']=$operate['timelong'];
                $pro['endtime']=$operate['timetype']==1?$operate['endtime']:(time()+$params['endtime']);
                $pro['sn']=$operate['acode'];
                if($operate['timetype']>1){
                    $changewin=isset($operate['changewin'])?$operate['changewin']:1;
                    switch ($changewin) {
                        case 2:// 区间
                            $sn = $this->model->daytraderisk('proid='.$pro['id'].' and endtime<='.($operate['endtime']+$params['endtime']).' and endtime >'.($operate['endtime']+$params['endtime']-$operate['timelong']),['sn', 'id']);
                            $pro['sn']=isset($sn['sn'])&&!empty($sn['sn'])?$sn['sn']:$operate['acode'];
                            if(isset($sn['id'])&&!empty($sn['id'])){ $pro['riskid'] = $sn['id'];}
                            break;
                        default://第一局
                            $pro['sn']=($operate['acode']+1);
                            $sn = $this->model->daytraderisk('proid='.$pro['id'].' and sn="'.$pro['sn'].'"',['id']);
                            if(isset($sn['id'])&&!empty($sn['id'])){ $pro['riskid'] = $sn['id'];}
                            break;
                    }
                }else{
                    $sn=[];//初始化sn
                    if($user['pid']>0){
                       $sn = $this->model->daytraderisk('proid='.$pro['id'].' and aid='.$user['pid'].' and sn="'.$operate['acode'].'"',['id']);//当前局 pid大于0时
                    }
                    if(empty($sn)){
                        $sn = $this->model->daytraderisk('proid='.$pro['id'].' and sn="'.$operate['acode'].'"',['id']);//当前局 平台
                    }
                    if(isset($sn['id'])&&!empty($sn['id'])){ $pro['riskid'] = $sn['id']; }
                }
            }
        }
        //判断其他参数
        if($params['money_type']==1){
           if($user['amount']<$params['order_price']) return $this->echoJson(Lang::get('Amountfew'));  //用戶金額
        }elseif($params['money_type']==2){
           if($user['giftamount']<$params['order_price']) return $this->echoJson(Lang::get('Amountfew')); //虛擬金額
        }
        //获取产品现价
        $price = $this->model->getprice($pro['procode']);
        if(empty($price['price'])){
            return $this->echojson(Lang::get('Ordererror'));
        }
        //获取手续费
        $sx_fee = (new CommonModel())->getBaseinfo('keyname="payment"','content')['content']['order'];
        $sx_fee = ($sx_fee*$params['order_price'])/100;
        
        //算单
        $params=[
            'order_no'=>getNumID(6,'order',1),//年月日加8位计数,order文件计数名称，1代表类别，1订单
            'type'=>$params['money_type'],
            'aid'=>$user['aid'],
            'pid'=>$user['pid'],
            'sn'=>$pro['sn'],
            'proid'=>$pro['id'],
            'proname'=>$pro['title'],
            'titles'=>$pro['titles'],
            'procode'=>$pro['procode'],
            'money'=>$params['order_price'],
            'endtime'=>isset($pro['endtime'])?$pro['endtime']:(time()+$pro['timelong']), 
            'updown'=>$params['order_type'],
            'riskid'=>$pro['riskid'],
            'buyprice'=>$price['price'],
            'sx_fee'=>$sx_fee,
            'status'=>1,
            'createtime'=>date('Y-m-d H:i:s',time())
        ];
        (new CommonModel())->startTrans();
        try {
            if($params['type']==1){
                $money=($user['amount']-$params['money']);
                $info = (new CommonModel())->updateAccount('aid='.$user['aid'],['amount'=>$money]);
            }elseif($params['type']==2){
                $money=($user['giftamount']-$params['money']);
                $info = (new CommonModel())->updateAccount('aid='.$user['aid'],['giftamount'=>$money]);
            }
            $id=$this->model->addorder($params);
            if($id){
                $data=[
                    'orderid'=>$id,
                    'sn'=>$pro['sn'],
                    'type'=>$params['type'],
                    'proid'=>$pro['id'],
                    'amount'=>$user['amount'],
                    'money'=>$params['money'],
                    'createtime'=>time()
                ];
                $this->model->addorderlog($data);
            }
            (new CommonModel())->commit();
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));
        }
    }

    /**
     * 订单结算settleorder
     * @param array $settleorder 
     * @param array $where 
     */ 
    public function settleorder(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['id'])) return $this->echoJson(Lang::get('Proempty'));
        //获取订单
        $order = $this->model->orderinfo('id='.$params['id']);
        if(isset($order['status']) && $order['status']==2 && $order['win']>0){
            return $this->echojson($this->success);
        }
        //判斷用户id
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['aid','amount','giftamount','pid']); //获取用户资金
        //獲取運營參數
        if(!empty($order['riskid'])){ $pro = $this->model->daytraderisk('id = '.$order['riskid'],['win']); }
        //获取输赢
        $win=0;
        switch (true) {
            case $order['win']==0:
                if(isset($pro['win'])&&!empty($pro['win'])){
                    switch ($pro['win']) {
                        case 1:
                            $win = $order['updown']==2 ? 1:2;  //买涨赢，买涨亏
                            break;
                        case 2:
                            $win = $order['updown']==1 ? 1:2;  //买跌赢，买跌亏
                            break;
                    }
                }else{
                    $chance=(new CommonModel())->getBaseinfo('keyname="chance"','content');
                    $chance=isset($chance['content']['win'])&&!empty($chance['content']['win'])?($chance['content']['win']/100):0.5;
                    if (probability($chance)) {
                        $win=1;
                    } else {
                        $win=2;
                    }
                }
                break;
            default:
                $win=$order['win'];
                break;
        }
        //根据输赢计算产品卖出价格
        $nowprice=$this->model->getprice($order['procode']);
        $rands=$this->model->random(['point_top'=>$nowprice['point_top'],'point_low'=>$nowprice['point_low']]);
        switch ($win) {
            case 1:
                if($order['updown']==2){
                    $price= $nowprice['price']>$order['buyprice']?$nowprice['price']: round(($order['buyprice']+($rands*$nowprice['rands'])),$nowprice['length']);
                }else{
                    $price= $nowprice['price']<$order['buyprice']?$nowprice['price']: round(($order['buyprice']-($rands*$nowprice['rands'])),$nowprice['length']);
                }
                break;
            case 2:
                if($order['updown']==2){
                    $price= $nowprice['price']<$order['buyprice']?$nowprice['price']: round(($order['buyprice']-($rands*$nowprice['rands'])),$nowprice['length']);
                }else{
                    $price= $nowprice['price']>$order['buyprice']?$nowprice['price']: round(($order['buyprice']+($rands*$nowprice['rands'])),$nowprice['length']);
                }
                break;
        }
        //返回数据
        $amount = $win==1 ? round(($order['money']*2-$order['sx_fee']),2) : 0 ;
        (new CommonModel())->startTrans();
        try {
            if($order['type']==1){
                (new CommonModel())->updateAccount('aid='.$user['aid'],['amount'=>($user['amount']+$amount)]);
                $backamount=$user['amount']+$amount;
            }elseif($order['type']==2){
                (new CommonModel())->updateAccount('aid='.$user['aid'],['giftamount'=>($user['giftamount']+$amount)]);
                $backamount=$user['giftamount']+$amount;
            }
            $this->model->updateOrder('id='.$order['id'],['status'=>2,'sellprice'=>$price,'win'=>$win]);
            if($order['id']){
                $data=[
                    'backamount'=>$backamount,
                    'backmoney'=>$amount,
                    'win'=>$win,
                    'settletime'=>time()
                ];
                $this->model->updateorderlog($order['id'],$data);
            }
            (new CommonModel())->commit();
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));
        }
    }
}